<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>一个简单的JDBC基础模板 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-09-04 20:55">
      September 4, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.6k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      28
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-一个简单的JDBC基础模板"><a href="#学习笔记-一个简单的JDBC基础模板" class="headerlink" title="学习笔记 : 一个简单的JDBC基础模板"></a>学习笔记 : 一个简单的JDBC基础模板</h2><p><em>最近在 GitHub 上又结识了一个小伙伴,看他最近在学习 JDBC 方面的知识,看到他所写的代码让我顿时回忆起自己初学编程的自己,所以想帮帮他,继而把前些日子写的 JDBC 基础模板整理了一下并给他提了一个 PR,详情请参考 : <a href="https://github.com/qinjiajuny/JDBCLearning/pull/4" target="_blank" rel="noopener">https://github.com/qinjiajuny/JDBCLearning/pull/4</a></em></p>
<ol>
<li><p><em>tb_user : 用户信息数据表</em></p>
<div class="hljs"><pre><code class="hljs sql"><span class="hljs-comment">-- auto-generated definition</span>
<span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> tb_user
(
    <span class="hljs-keyword">id</span>        <span class="hljs-built_in">int</span> auto_increment primary <span class="hljs-keyword">key</span>,
    <span class="hljs-keyword">name</span>      <span class="hljs-built_in">varchar</span>(<span class="hljs-number">10</span>) <span class="hljs-literal">null</span>,
    age       <span class="hljs-built_in">int</span>         <span class="hljs-literal">null</span>,
    gender    <span class="hljs-built_in">char</span>(<span class="hljs-number">2</span>)     <span class="hljs-literal">null</span>,
    <span class="hljs-keyword">password</span>  <span class="hljs-built_in">varchar</span>(<span class="hljs-number">15</span>) <span class="hljs-literal">null</span>,
    telephone <span class="hljs-built_in">varchar</span>(<span class="hljs-number">11</span>) <span class="hljs-literal">null</span>,
    birthday  <span class="hljs-built_in">date</span>        <span class="hljs-literal">null</span>
);</code></pre></div>
</li>
<li><p><em>db.properties : 数据库连接配置文件</em></p>
<div class="hljs"><pre><code class="hljs sh"><span class="hljs-comment"># Database configuration information (Server version: 8.0.11 MySQL Community Server - GPL)</span>
Url=jdbc:mysql://localhost/database-name?useSSL=<span class="hljs-literal">false</span>&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=<span class="hljs-literal">true</span>
UserName=
UserPassword=
DriverName=com.mysql.cj.jdbc.Driver</code></pre></div>
</li>
<li><p><em>ConfigUtil.java : 读取数据库连接配置文件的工具类</em></p>
<div class="hljs"><pre><code class="hljs java">package pers.huangyuhui.curd.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @project: curd-demo
 * @description: 读取数据库配置文件的工具类
 * @author: 黄宇辉
 * @date: 8/22/2019-3:49 PM
 * @version: 1.0
 * @website: https://yubuntu0109.github.io/
 */
class ConfigUtil &#123;

    private ConfigUtil() &#123;
    &#125;

    private static Properties properties;
    // 读取数据库配置文件
    private static InputStream inputStream = ConfigUtil.class.getResourceAsStream("/db.properties");

    static &#123;
        try &#123;
            properties = new Properties();
            properties.load(inputStream);
            properties.getProperty("Url");
            properties.getProperty("UserName");
            properties.getProperty("UserPassword");
            properties.getProperty("DriverName");
        &#125; catch (FileNotFoundException e) &#123;
            System.err.println("error: not found db.properties file");
            e.printStackTrace();
        &#125; catch (IOException e) &#123;
            e.printStackTrace();
        &#125;

    &#125;

    //获取数据库配置
    static Properties getProperties() &#123;
        return properties;
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>DBUtil : 连接数据库的工具类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd.utils;

<span class="hljs-keyword">import</span> java.sql.Connection;
<span class="hljs-keyword">import</span> java.sql.DriverManager;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: curd-demo
 * <span class="hljs-doctag">@description</span>: 链接数据库的工具类
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/22/2019-3:30 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DBUitl</span> </span>&#123;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Connection connection;

    <span class="hljs-comment">//获取数据库配置信息</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String URL = ConfigUtil.getProperties().getProperty(<span class="hljs-string">"Url"</span>);
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String USER = ConfigUtil.getProperties().getProperty(<span class="hljs-string">"UserName"</span>);
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String PASSWORD = ConfigUtil.getProperties().getProperty(<span class="hljs-string">"UserPassword"</span>);
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String DRIVER_NAME = ConfigUtil.getProperties().getProperty(<span class="hljs-string">"DriverName"</span>);

    <span class="hljs-comment">//加载数据库驱动</span>
    <span class="hljs-keyword">static</span> &#123;
        <span class="hljs-keyword">try</span> &#123;
            Class.forName(DRIVER_NAME);
        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;
            System.err.println(<span class="hljs-string">"error: fail to init the driver of database"</span>);
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ExceptionInInitializerError(e);
        &#125;
    &#125;

    <span class="hljs-comment">//获取数据库连接</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Connection <span class="hljs-title">getConnection</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">if</span> (connection == <span class="hljs-keyword">null</span>) &#123;
            <span class="hljs-keyword">try</span> &#123;
                connection = DriverManager.getConnection(URL, USER, PASSWORD);
            &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;
                e.printStackTrace();
            &#125;
        &#125;
        <span class="hljs-keyword">return</span> connection;
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>User.java : 用户信息类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd.bean;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: curd-demo
 * <span class="hljs-doctag">@description</span>: 用户基础信息
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/22/2019-3:22 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;
    <span class="hljs-keyword">private</span> Integer id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> Integer age;
    <span class="hljs-keyword">private</span> String gender;
    <span class="hljs-keyword">private</span> String password;
    <span class="hljs-keyword">private</span> String telephone;
    <span class="hljs-keyword">private</span> String birthday;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> id;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(Integer id)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.id = id;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.name = name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> age;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(Integer age)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.age = age;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getGender</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> gender;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setGender</span><span class="hljs-params">(String gender)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.gender = gender;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPassword</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> password;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPassword</span><span class="hljs-params">(String password)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.password = password;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getTelephone</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> telephone;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTelephone</span><span class="hljs-params">(String telephone)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.telephone = telephone;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getBirthday</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> birthday;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setBirthday</span><span class="hljs-params">(String birthday)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.birthday = birthday;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">"User&#123;"</span> +
                <span class="hljs-string">"id="</span> + id +
                <span class="hljs-string">", name='"</span> + name + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", age="</span> + age +
                <span class="hljs-string">", gender='"</span> + gender + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", password='"</span> + password + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", telephone='"</span> + telephone + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", birthday='"</span> + birthday + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">'&#125;'</span>;
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>UserDao.java : 数据访问层</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd.dao;

<span class="hljs-keyword">import</span> pers.huangyuhui.curd.bean.User;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.utils.DBUitl;

<span class="hljs-keyword">import</span> java.sql.Connection;
<span class="hljs-keyword">import</span> java.sql.PreparedStatement;
<span class="hljs-keyword">import</span> java.sql.ResultSet;
<span class="hljs-keyword">import</span> java.sql.SQLException;
<span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: curd-demo
 * <span class="hljs-doctag">@description</span>: 数据访问层(DAO):可利用JDK8新特性Lambda来优化此程序
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/22/2019-3:28 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserDao</span> </span>&#123;

    <span class="hljs-comment">//获取数据库连接</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Connection connection = DBUitl.getConnection();

    <span class="hljs-comment">//添加用户信息</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">insertNewUser</span><span class="hljs-params">(User user)</span> </span>&#123;
        String sql = <span class="hljs-string">"insert into tb_user(name, age, gender, password, telephone, birthday) values (?,?,?,?,?,?)"</span>;
        <span class="hljs-keyword">try</span> (PreparedStatement preparedStatement = connection.prepareStatement(sql)) &#123;
            preparedStatement.setString(<span class="hljs-number">1</span>, user.getName());
            preparedStatement.setInt(<span class="hljs-number">2</span>, user.getAge());
            preparedStatement.setString(<span class="hljs-number">3</span>, user.getGender());
            preparedStatement.setString(<span class="hljs-number">4</span>, user.getPassword());
            preparedStatement.setString(<span class="hljs-number">5</span>, user.getBirthday());
            preparedStatement.setString(<span class="hljs-number">6</span>, user.getTelephone());
            <span class="hljs-keyword">return</span> preparedStatement.executeUpdate() &gt; <span class="hljs-number">0</span>;
        &#125; <span class="hljs-keyword">catch</span> (SQLException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    &#125;

    <span class="hljs-comment">//查询所有用户信息</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;User&gt; <span class="hljs-title">selectAllUser</span><span class="hljs-params">()</span> </span>&#123;
        String sql = <span class="hljs-string">"select id, name, age, gender, password, telephone, birthday from tb_user"</span>;
        List&lt;User&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        <span class="hljs-keyword">try</span> (PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) &#123;
            <span class="hljs-keyword">while</span> (resultSet.next()) &#123;
                User user = <span class="hljs-keyword">new</span> User();
                user.setId(resultSet.getInt(<span class="hljs-string">"id"</span>));
                user.setName(resultSet.getString(<span class="hljs-string">"name"</span>));
                user.setAge(resultSet.getInt(<span class="hljs-string">"age"</span>));
                user.setGender(resultSet.getString(<span class="hljs-string">"gender"</span>));
                user.setPassword(resultSet.getString(<span class="hljs-string">"password"</span>));
                user.setTelephone(resultSet.getString(<span class="hljs-string">"telephone"</span>));
                user.setBirthday(resultSet.getString(<span class="hljs-string">"birthday"</span>));
                list.add(user);
            &#125;
            <span class="hljs-keyword">return</span> list;
        &#125; <span class="hljs-keyword">catch</span> (SQLException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    &#125;

    <span class="hljs-comment">//更新用户信息</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">updateUserById</span><span class="hljs-params">(User user)</span> </span>&#123;
        String sql = <span class="hljs-string">"UPDATE tb_user SET name = ? , gender = ? , age = ? , password = ?, birthday = ?, telephone = ? where id = ?"</span>;
        <span class="hljs-keyword">try</span> &#123;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(<span class="hljs-number">1</span>, user.getName());
            preparedStatement.setString(<span class="hljs-number">2</span>, user.getGender());
            preparedStatement.setInt(<span class="hljs-number">3</span>, user.getAge());
            preparedStatement.setString(<span class="hljs-number">4</span>, user.getPassword());
            preparedStatement.setString(<span class="hljs-number">5</span>, user.getBirthday());
            preparedStatement.setString(<span class="hljs-number">6</span>, user.getTelephone());
            preparedStatement.setInt(<span class="hljs-number">7</span>, user.getId());
            <span class="hljs-keyword">return</span> preparedStatement.executeUpdate() &gt; <span class="hljs-number">0</span>;
        &#125; <span class="hljs-keyword">catch</span> (SQLException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    &#125;

    <span class="hljs-comment">//删除用户信息</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">deleteUserById</span><span class="hljs-params">(Integer id)</span> </span>&#123;
        String sql = <span class="hljs-string">"delete from tb_user where id = ?"</span>;
        <span class="hljs-keyword">try</span> &#123;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(<span class="hljs-number">1</span>, id);
            <span class="hljs-keyword">return</span> preparedStatement.executeUpdate() &gt; <span class="hljs-number">0</span>;
        &#125; <span class="hljs-keyword">catch</span> (SQLException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    &#125;

&#125;</code></pre></div>
</li>
<li><p><em>UserService.java : 业务逻辑层</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd.service;

<span class="hljs-keyword">import</span> pers.huangyuhui.curd.bean.User;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: curd-demo
 * <span class="hljs-doctag">@description</span>: 业务逻辑层(Service)
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/22/2019-3:29 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserService</span> </span>&#123;

    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">getAllUser</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">addUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">updateUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(Integer id)</span></span>;
&#125;</code></pre></div>
</li>
<li><p><em>UserServiceImpl.java : 业务逻辑层的实现类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd.service.impl;

<span class="hljs-keyword">import</span> pers.huangyuhui.curd.bean.User;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.dao.UserDao;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.service.UserService;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: curd-demo
 * <span class="hljs-doctag">@description</span>: 业务逻辑层的实现类
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/22/2019-3:29 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserService</span> </span>&#123;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> UserDao userDao = <span class="hljs-keyword">new</span> UserDao();

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;User&gt; <span class="hljs-title">getAllUser</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> userDao.selectAllUser();
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">addUser</span><span class="hljs-params">(User user)</span> </span>&#123;
        <span class="hljs-keyword">return</span> userDao.insertNewUser(user);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">updateUser</span><span class="hljs-params">(User user)</span> </span>&#123;
        <span class="hljs-keyword">return</span> userDao.updateUserById(user);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(Integer id)</span> </span>&#123;
        <span class="hljs-keyword">return</span> userDao.deleteUserById(id);
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>AppTest.java : 程序测试类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.curd;

<span class="hljs-keyword">import</span> org.junit.BeforeClass;
<span class="hljs-keyword">import</span> org.junit.Test;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.bean.User;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.service.UserService;
<span class="hljs-keyword">import</span> pers.huangyuhui.curd.service.impl.UserServiceImpl;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-comment">/**
 * Unit test for simple App.
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppTest</span> </span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> UserService userService;

    <span class="hljs-meta">@BeforeClass</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> </span>&#123;
        userService = <span class="hljs-keyword">new</span> UserServiceImpl();
    &#125;

    <span class="hljs-comment">//test getAllUser() method</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printAllUser</span><span class="hljs-params">()</span> </span>&#123;
        List&lt;User&gt; allUsers = userService.getAllUser();
        System.out.println(<span class="hljs-string">"获取所有的用户信息 : "</span> + allUsers);
    &#125;

    <span class="hljs-comment">//test addUser method</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span> </span>&#123;
        User user = <span class="hljs-keyword">new</span> User();
        user.setName(<span class="hljs-string">"addUser"</span>);
        user.setGender(<span class="hljs-string">"男"</span>);
        user.setAge(<span class="hljs-number">0</span>);
        user.setPassword(<span class="hljs-string">"pwd"</span>);
        user.setTelephone(<span class="hljs-string">"000000"</span>);
        user.setBirthday(<span class="hljs-string">"0000-00-00"</span>);
        System.out.println(<span class="hljs-string">"是否成功添加用户信息 : "</span> + userService.addUser(user));
    &#125;


    <span class="hljs-comment">//test updateUser method</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span> </span>&#123;
        User user = <span class="hljs-keyword">new</span> User();
        user.setId(<span class="hljs-number">1</span>);
        user.setName(<span class="hljs-string">"updateUser"</span>);
        user.setGender(<span class="hljs-string">"女"</span>);
        user.setAge(<span class="hljs-number">0</span>);
        user.setPassword(<span class="hljs-string">"pwd"</span>);
        user.setTelephone(<span class="hljs-string">"111111"</span>);
        user.setBirthday(<span class="hljs-string">"1111-11-11"</span>);
        System.out.println(<span class="hljs-string">"是否成功更新用户信息 : "</span> + userService.updateUser(user));
    &#125;

    <span class="hljs-comment">//test deleteUser method</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">"是否成功删除用户信息 : "</span> + userService.deleteUser(<span class="hljs-number">1</span>));
    &#125;
&#125;</code></pre></div></li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/MySQL/">MySQL</a>
                    
                      <a class="hover-with-bg" href="/tags/Java/">Java</a>
                    
                      <a class="hover-with-bg" href="/tags/JDBC/">JDBC</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/09/05/Java%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8BFactory-Method-Pattern/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Java设计模式之Factory Method模式</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/09/04/Java%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8BTemplate-Method-Pattern/">
                        <span class="hidden-mobile">Java设计模式之Template Method模式</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "一个简单的JDBC基础模板&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
